package cn.cloudreal.cbms.system.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.system.service.PurviewService;
import cn.cloudreal.cbms.system.service.RoleService;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Purview;
import cn.cloudreal.cbms.vo.Role;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: CBMS
 * </p>
 * <p>
 * Description:用户管理查询数据服务层视图类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author Gaoxuejiao
 * @date 2012-07-17
 */
public class RoleAction extends ActionSupport
{
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(RoleAction.class);

    /**
     * 注入service 类
     */
    private RoleService roleService;
    /**
     * 注入service 类
     */
    private PurviewService purviewService;

    /** id */
    long id;

    /** 当前页 */
    int currentPage;

    /** 角色列表 */
    private List<Role> roleLists;

    /** 权限列表 */
    private List<Purview> purviewLists;

    /**
     * 角色实体信息
     */
    private Role role;

    /**
     * 权限
     */
    private Purview purview;

    /** 分页对象 */
    PageBean page;

    /** falg：1：查看，2：修改初始化，3：修改确认 ，4：新增保存 */
    String flag;

    /**
     * 权限id 拼接字符串
     */
    private String purviewIDs;

    /**
     * 列表
     * 
     * @return String
     */
    public String getRoleList()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction getRoleList() method,return String");
        }
        try
        {
            roleLists = new ArrayList<Role>();

            if (null == role)
            {
                role = new Role();
            }
            // 默认当前登录人地市
            UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute("logUser");
            role.setCity(userSession.getUsercity());

            // 实例化 page分页对象
            page = new PageBean(currentPage == 0 ? 1 : currentPage,
                    Constants.PAGE_SIZE);

            // 获取数据
            roleLists = roleService.getRoles(role, page);
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常信息 返回error
            log.error("Error RoleAction getRoleList() method,return String", e);
            return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit RoleAction getRoleList() method,return String");
        }
        return SUCCESS;
    }

    /**
     * 查看
     * 
     * @return
     */
    public String roleDetail()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction roleDetail() method,return String");
        }
        try
        {
            if (null != role)
            {
                // 获取当前对象
                role = roleService.getRole(role.getId());
                StringBuffer ss = new StringBuffer("[");
                if (null != role)
                {
                    // 操作范围值转换
                    if (null != role.getRoleRange())
                    {
                        Dictionary dic = DatadicContext.getInstance()
                                .getDatadicObject(role.getRoleRange(),
                                        Constants.ROLE_RANGE);
                        if (null != dic && null != dic.getDatavalue())
                        {
                            role.setRoleRange(dic.getClassname());
                        }
                    }
                    // 获取当前对象下所有权限信息
                    List<Purview> purviews = new ArrayList<Purview>();

                    purviews = purviewService.getPurviewsByRole(role.getRolecode());

                    purviewLists = new ArrayList<Purview>();
                    // 获取集合
                    purviewLists = purviewService.getAllPurviews(new Purview());

                    String purviewId = "";

                    boolean tempFlag = false;
                    for (int i = 0; i < purviewLists.size(); i++)
                    {
                        tempFlag = false;
                        // 获取集合单独对象
                        Purview pur = new Purview();
                        pur = purviewLists.get(i);

                        // 如果当前权限存在 则默认选中
                        for (int j = 0; j < purviews.size(); j++)
                        {
                            // 添加文字显示
                            purviewId += purviews.get(j).getActionName() + ",";

                            // 如果存在 则选中
                            if (pur.getId().equals(purviews.get(j).getId()))
                            {
                                tempFlag = true;
                                // 如果当前是父节点打开
                                if (pur.getParentId().intValue() == -1)
                                {
                                    ss.append("{ id:'"
                                            + pur.getId()
                                            + "',  pId:"
                                            + pur.getParentId()
                                            + ",   name:'"
                                            + pur.getActionName()
                                            + "',open:true, checked:true,chkDisabled:true},");
                                }
                                else
                                {
                                    ss.append("{ id:'"
                                            + pur.getId()
                                            + "',  pId:"
                                            + pur.getParentId()
                                            + ",   name:'"
                                            + pur.getActionName()
                                            + "', checked:true,chkDisabled:true},");
                                }
                                break;
                            }
                        }

                        // 如果没有存在的 则开始重新复制
                        if (!tempFlag)
                        {
                            // 如果当前是父节点打开
                            if (pur.getParentId().intValue() == -1)
                            {
                                ss.append("{ id:'" + pur.getId() + "',  pId:"
                                        + pur.getParentId() + ",   name:'"
                                        + pur.getActionName()
                                        + "',open:true,chkDisabled:true},");
                            }
                            else
                            {
                                ss.append("{ id:'" + pur.getId() + "',  pId:"
                                        + pur.getParentId() + ",   name:'"
                                        + pur.getActionName()
                                        + "',chkDisabled:true},");
                            }
                        }
                    }
                    if (purviewId.length() > 0)
                    {
                        role.setPurviewId(purviewId.substring(0,
                                purviewId.length() - 1));
                    }
                    flag = ss.substring(0, ss.toString().length() - 1)
                            .toString();
                }
                else
                {
                    flag = ss.toString();

                }
                flag += "];";
            }

        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error RoleAction roleDetail() method,return String edit",
                    e);
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 跳转到修改页面
     * 
     * @return SUCCESS
     */
    public String toRoleEdit()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction toRoleEdit() method,return String");
        }
        try
        {
            // 获取当前对象
            role = roleService.getRole(role.getId());
            StringBuffer ss = new StringBuffer("[");
            if (null != role)
            {
                // 获取当前对象下所有权限信息
                List<Purview> purviews = new ArrayList<Purview>();

                purviews = purviewService.getPurviewsByRole(role.getRolecode());

                purviewLists = new ArrayList<Purview>();
                // 获取集合
                purviewLists = purviewService.getAllPurviews(new Purview());

                String purviewId = "";
                purviewIDs = new String();
                boolean tempFlag = false;
                for (int i = 0; i < purviewLists.size(); i++)
                {
                    tempFlag = false;
                    // 获取集合单独对象
                    Purview pur = new Purview();
                    pur = purviewLists.get(i);

                    // 如果当前权限存在 则默认选中
                    for (int j = 0; j < purviews.size(); j++)
                    {

                        // 如果存在 则选中
                        if (pur.getId().equals(purviews.get(j).getId()))
                        {
                            // 添加文字显示
                            purviewId += purviews.get(j).getActionName() + ",";
                            if (null != purviews.get(j).getId())
                            {
                                // 拼接 id
                                purviewIDs += purviews.get(j).getId() + ",";
                            }

                            tempFlag = true;
                            // 如果当前是父节点打开
                            if (pur.getParentId().intValue() == -1)
                            {
                                ss.append("{ id:'" + pur.getId() + "',  pId:"
                                        + pur.getParentId() + ",   name:'"
                                        + pur.getActionName()
                                        + "',open:true, checked:true},");
                            }
                            else
                            {
                                ss.append("{ id:'" + pur.getId() + "',  pId:"
                                        + pur.getParentId() + ",   name:'"
                                        + pur.getActionName()
                                        + "', checked:true},");
                            }
                            break;
                        }
                    }

                    // 如果没有存在的 则开始重新复制
                    if (!tempFlag)
                    {
                        // 如果当前是父节点打开
                        if (pur.getParentId().intValue() == -1)
                        {
                            ss.append("{ id:'" + pur.getId() + "',  pId:"
                                    + pur.getParentId() + ",   name:'"
                                    + pur.getActionName() + "',open:true},");
                        }
                        else
                        {
                            ss.append("{ id:'" + pur.getId() + "',  pId:"
                                    + pur.getParentId() + ",   name:'"
                                    + pur.getActionName() + "'},");
                        }
                    }
                }
                if (purviewId.length() > 0)
                {
                    role.setPurviewId(purviewId.substring(0,
                            purviewId.length() - 1));
                    purviewIDs = purviewIDs.substring(0,
                            purviewIDs.length() - 1);
                }
                flag = ss.substring(0, ss.toString().length() - 1).toString();

            }
            else
            {
                flag = ss.toString();
            }
            flag += "];";
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error RoleAction toRoleEdit() method,return String edit",
                    e);
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 执行修改页面
     * 
     * @return SUCCESS
     */
    public String doRoleEdit()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction doRoleEdit() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 默认当前登录人地市
            UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute("logUser");
            role.setCity(userSession.getUsercity());

            // 如果不为空 执行修改
            if (null != role && null != role.getRolecode())
            {
                roleService.updateRole(role);
            }
            out.print("true");
            out.flush();
            out.close();
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error RoleAction doRoleEdit() method,return String ", e);
            out.print("error");
            out.flush();
            out.close();
        }
        return null;
    }

    /**
     * 跳转到新增页面
     * 
     * @return SUCCESS
     */
    public String toRoleAdd()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction toRoleAdd() method,return String");
        }
        try
        {
            purviewLists = new ArrayList<Purview>();
            // 获取集合
            purviewLists = purviewService.getAllPurviews(new Purview());

            StringBuffer ss = new StringBuffer("[");
            for (int i = 0; i < purviewLists.size(); i++)
            {
                // 获取集合单独对象
                Purview pur = new Purview();
                pur = purviewLists.get(i);

                // 如果当前是父节点打开
                if (pur.getParentId().intValue() == -1)
                {
                    ss.append("{ id:'" + pur.getId() + "',  pId:"
                            + pur.getParentId() + ",   name:'"
                            + pur.getActionName() + "',open:true},");
                }
                else
                {
                    ss.append("{ id:'" + pur.getId() + "',  pId:"
                            + pur.getParentId() + ",   name:'"
                            + pur.getActionName() + "'},");
                }
            }

            if (null != purviewLists && purviewLists.size() > 0)
            {
                flag = ss.substring(0, ss.toString().length() - 1).toString();
            }
            else
            {
                flag = ss.toString();
            }

            flag += "];";
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error RoleAction toRoleAdd() method,return String edit",
                    e);
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 保存角色
     * 
     * @return SUCCESS
     */
    public String doRoleAdd()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction doRoleAdd() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            // 如果不为空
            if (null != role)
            {
                // 默认当前登录人地市
                UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
                        .getSession()
                        .getAttribute("logUser");
                role.setCity(userSession.getUsercity());

                // 获取角色权限字符串截取
                roleService.addRole(role);
                role = new Role();
                out.print("true");
                out.flush();
                out.close();
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error RoleAction doRoleAdd() method,return String ", e);
            out.print("error");
            out.flush();
            out.close();
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit RoleAction doRoleAdd() method,return String ");
        }
        return null;
    }

    /**
     * 验证角色编号是否已经存在
     * 
     * @return
     */
    public String isExistRoleCode()
    {

        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction isExistRoleCode() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            String roleCode = URLDecoder.decode(role.getRolecode(), "UTF-8");

            role.setRolecode(roleCode);
            // 获取返回值
            boolean flagStr = roleService.isUseRolecode(role);

            out.print(flagStr);
            out.flush();
            out.close();
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error RoleAction isExistRoleCode() method,return String ",
                    e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit RoleAction isExistRoleCode() method,return String ");
        }
        return null;
    }

    /**
     * 验证角色名称是否已经存在
     * 
     * @return
     */
    public String isExistRoleName()
    {

        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction isExistRoleCode() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            String roleName = URLDecoder.decode(role.getRolename(), "UTF-8");

            role.setRolename(roleName);

            // 默认当前登录人地市
            UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute("logUser");
            role.setCity(userSession.getUsercity());

            // 获取返回值
            boolean flagStr = roleService.isUseRolecode(role);

            out.print(flagStr);
            out.flush();
            out.close();
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error RoleAction isExistRoleCode() method,return String ",
                    e);
            out.print("error");
            out.flush();
            out.close();
            // return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit RoleAction isExistRoleCode() method,return String ");
        }
        return null;
    }

    /**
     * 删除
     * 
     * @return SUCCESS
     */
    public String delete()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter RoleAction delete() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        { // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 如果对象不为null 执行删除
            if (null != role)
            {
                String roleCode = URLDecoder.decode(role.getRolecode(), "UTF-8");
                role.setRolecode(roleCode);
                if (roleService.isUseRoleUser(roleCode))
                {
                    out.print("exist");
                    return null;
                }
                // 判断当前是否有用户在使用该角色

                roleService.delRole(role);
                out.print("success");
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志 返回Error
            log.error("Error RoleAction delete() method,return String", e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit RoleAction delete() method,return String ");
        }
        return null;
    }


    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getFlag()
    {
        return flag;
    }

    public void setFlag(String flag)
    {
        this.flag = flag;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    public List<Role> getRoleLists()
    {
        return roleLists;
    }

    public void setRoleLists(List<Role> roleLists)
    {
        this.roleLists = roleLists;
    }

    public Role getRole()
    {
        return role;
    }

    public void setRole(Role role)
    {
        this.role = role;
    }

    public RoleService getRoleService()
    {
        return roleService;
    }

    public void setRoleService(RoleService roleService)
    {
        this.roleService = roleService;
    }

    public PurviewService getPurviewService()
    {
        return purviewService;
    }

    public void setPurviewService(PurviewService purviewService)
    {
        this.purviewService = purviewService;
    }

    public List<Purview> getPurviewLists()
    {
        return purviewLists;
    }

    public void setPurviewLists(List<Purview> purviewLists)
    {
        this.purviewLists = purviewLists;
    }

    public Purview getPurview()
    {
        return purview;
    }

    public void setPurview(Purview purview)
    {
        this.purview = purview;
    }

    public String getPurviewIDs()
    {
        return purviewIDs;
    }

    public void setPurviewIDs(String purviewIDs)
    {
        this.purviewIDs = purviewIDs;
    }

}
